
# 读取文件
# First try utf-8 encoding, if it fails, try gbk encoding
try:
    file = open('test.txt', 'r', encoding='utf-8')
except UnicodeDecodeError:
    file = open('test.txt', 'r', encoding='gbk')

print(file.read())
file.close()


file = open('test.txt', 'r', encoding='utf-8')
for line in file:
    print(line, end='')
file.close()

file = open('test.txt', 'r', encoding='utf-8')
lines = file.readlines()
for line in lines:
    print(line, end='')
file.close()

file = None
try:
    file = open('test.txt', 'r', encoding='utf-8')
    print(file.read())
except FileNotFoundError:
    print('无法打开指定的文件!')
except LookupError:
    print('指定了未知的编码!')
except UnicodeDecodeError:
    print('读取文件时解码错误!')
finally:
    if file:
        file.close()

'''
要复制的图片文件很大，一次将文件内容直接读入内存中可能会造成非常大的内存开销，
为了减少对内存的占用，可以为read方法传入size参数来指定每次读取的字节数，通过循环读取和写入的方式来完成上面的操作，代码如下所示。
'''
try:
    with open('guido.jpg', 'rb') as file1, open('吉多.jpg', 'wb') as file2:
        data = file1.read(512)
        while data:
            file2.write(data)
            data = file1.read()
except FileNotFoundError:
    print('指定的文件无法打开.')
except IOError:
    print('读写文件时出现错误.')
print('程序执行结束.')        